<template>
  <view
    class="code"
    button
    :class="{ disabled: btnDisabled }"
    @tap="handleSendCode"
  >
    获取验证码
   <text class="code__count">({{count}}s)</text>
  </view>
</template>
<script>
import { isMobile } from '@/utils'
import { SUCCESS, sendCode } from '@/api'

export default {
  props: ['scene', 'mobile'],
  data () {
    return {
      count: 30,
      btnDisabled: false
    }
  },
  methods: {
    async handleSendCode () {
      if (this.btnDisabled) {
        return
      }
      if (!isMobile(this.mobile)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
          duration: 2000
        })
        return
      }

      const res = await sendCode({ scene: this.scene, mobile: this.mobile })
      console.log('res', res)
      if (res.code === SUCCESS) {
        uni.showToast({
          title: '发送成功',
          duration: 2000
        })
        this.btnDisabled = true

        const timer = setInterval(() => {
          this.count--
          if (this.count <= 0) {
            this.count = 30
            this.btnDisabled = false
            clearInterval(timer)
          }
        }, 1000)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.code {
  background: #8C6540;
  font-size: 26rpx;
  color: #FCE9CB;
  border-radius: 19rpx;
  white-space: nowrap;
  padding: 20rpx 15rpx;
  margin-right: 10rpx;
  &__count {
    font-size: .8em;
  }
}
.disabled {
  opacity: .7
}
</style>
